<?php

namespace app\api\service;

use think\facade\Db;

class GoodsCategoryService
{
    /**
     * 获取首页分类
     * */
    public static function getHomeCategoryList($store_id)
    {
        $categories = Db::name('goods_category')
            ->where(['store_id' => $store_id, 'status' => 1, 'is_home' => 1])
            ->field('id,name')
            ->select();

        return $categories;
    }

    /**
     * 获取子分类
     * */
    public static function findChildCategory($category_id)
    {

        $categories = Db::name('goods_category')
            ->where(['parent_id' => $category_id, 'status' => 1])
            ->field('id,name,icon')
            ->withAttr('icon', function ($value) {
                return empty($value) ? $value : request()->domain() . $value;
            })->select();

        return $categories;
    }

    /**
     * 一级分类
     */
    public static function categoryList($store_id)
    {
        $categories = Db::name('goods_category')
            ->where(['store_id' => $store_id, 'status' => 1, 'parent_id' => 0])
            ->field('id,parent_id,name,icon')
            ->order('sort', 'desc')
            ->withAttr('icon', function ($value) {
                return empty($value) ? $value : request()->domain() . $value;
            })->select();
        return $categories;
    }

    /**
     * 二级分类
     */
    public static function secondCategoryList($store_id, $cid)
    {
        $categories = Db::name('goods_category')
        ->where(['store_id' => $store_id, 'status' => 1, 'parent_id' => $cid])
        ->field('id,parent_id,name,icon')
        ->order('sort', 'desc')
        ->withAttr('icon', function ($value) {
            return empty($value) ? $value : request()->domain() . $value;
        })->select();
    return $categories;
    }

    /**
     * 获取所有分类
     * */
    public static function getCategoryList($store_id)
    {
        $categories = Db::name('goods_category')
            ->where(['store_id' => $store_id, 'status' => 1])
            ->field('id,parent_id,name,icon')
            ->withAttr('icon', function ($value) {
                return empty($value) ? $value : request()->domain() . $value;
            })->select();

        $items = array();
        foreach ($categories as $value) {
            $items[$value['id']] = $value;
        }

        $tree = array();
        foreach ($items as $key => $item) {
            if (isset($items[$item['parent_id']])) {
                $items[$item['parent_id']]['children'][] = &$items[$key];
            } else {
                $tree[] = &$items[$key];
            }
        }

        return $tree;
    }

}
